﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Drawing.Drawing2D;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading;
using System.Threading.Tasks;
using System.Windows.Forms;

namespace WinFormStore.Store
{
    public partial class FrmHome : Form
    {
         Socket Client;
        Thread thrClient = null;
        public FrmHome()
        {
            InitializeComponent();
        }
        private void Connect()
        {
            IPAddress address=IPAddress.Parse("127.0.0.1");
            IPEndPoint ipe = new IPEndPoint(address, int.Parse("123"));
            Client = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            try
            {
                this.textBox2.AppendText("正在与服务器连接"+"\r\n");
                Client.Connect(ipe);
            }
            catch (Exception e)
            {
                MessageBox.Show("连接失败"+e);
            }
            this.textBox2.AppendText("连接成功");
            thrClient = new Thread(ReceiveMsg);
            thrClient.IsBackground = true;
            thrClient.Start();

        }

        private void ReceiveMsg()
        {
            while (true)
            {
                byte[] arrMsgRec = new byte[1024*1024*2];
                int length = Client.Receive(arrMsgRec);
                if (length==0)
                {
                    Invoke(new Action(()=>this.textBox2.AppendText("断开连接")));
                    break;
                }
                else
                {
                    string strMsg=Encoding.UTF8.GetString(arrMsgRec,0,length);
                    string msg="[接收]"+strMsg+Environment.NewLine;
                    Invoke(new Action(() => this.textBox2.AppendText(msg)));
                }
            }
        }

        private void FrmHome_Load(object sender, EventArgs e)
        {
            PictureBeCricle();
            this.textBox2.ScrollBars = ScrollBars.Vertical;
            this.lblUserName.Text=LoginConfig.SalesManName;
            Connect();
        }

        #region 将头像框变成圆形
        private void PictureBeCricle()
        {
            GraphicsPath gp = new GraphicsPath();
            gp.AddEllipse(picAvatar.ClientRectangle); // 假设pictureBox1是你要变成圆形的PictureBox
            Region region = new Region(gp);
            picAvatar.Region = region;
            gp.Dispose();
            region.Dispose();
        }

        #endregion

        private void btnSend_Click(object sender, EventArgs e)
        {
            string strMsg = "来自" +LoginConfig.SalesManName+":"+textBox1.Text+DateTime.Now;
            byte[] arrMsg=Encoding.UTF8.GetBytes(strMsg);
            Client.Send(arrMsg);
            Invoke(new Action(() => textBox2.AppendText("[发送]"+textBox1.Text+Environment.NewLine)));
        }
    }
}
